import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户认证token
    token: uni.getStorageSync('token') || '',
    // 用户ID
    userId: uni.getStorageSync('userId') || '',
    // 用户信息
    userInfo: uni.getStorageSync('userInfo') || {},
    // 系统信息
    systemInfo: uni.getStorageSync('systemInfo') || { custom: {} }
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      uni.setStorageSync('token', token)
    },

    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
      uni.setStorageSync('userInfo', userInfo)
    },

    SET_SYSTEMINFO: (state, systemInfo) => {
      state.systemInfo = systemInfo
      uni.setStorageSync('systemInfo', systemInfo)
    }
  },

  actions: {
    // 用户登录
    login({ commit }, userInfo) {
      return new Promise(async (resolve, reject) => {
        // TODO: 用户登录处理，根据需求修改
        const res = await login(userInfo)
        commit('SET_TOKEN', res.data.token)
        resolve(res)
      })
    },

    // 获取用户信息
    userInfo({ commit }) {
      return new Promise(async (resolve, reject) => {
        // TODO: 获取用户信息处理，根据需求修改
        try {
          const res = await getUserInfo()
          commit('SET_USERINFO', res.data)
          resolve(res)
        } catch (e) {
          reject(e)
        }
      })
    },

    // 注销session
    FedLogOut({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_USERINFO', {})
        resolve()
      })
    }
  },

  getters: {
    token: state => state.token,
    userId: state => state.userId,
    userInfo: state => state.userInfo,
    systemInfo: state => state.systemInfo
  }
})
